package com.xinkao.example.service.impl;

import cn.hutool.core.util.StrUtil;
import com.xinkao.example.dao.UploadFileDao;
import com.xinkao.example.util.RandomUtils;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.InputStream;

/**
 * minio 工具类
 * @Author lililiang
 * @Date 2021/7/9 10:53
 */
@Service
public class MinioServiceImpl {


	@Resource
	private MinioClient client;
	@Value("${minio.bucket}")
	private String bucket;

	public static String IMGSUF = "BMP,JPG,JPEG,PNG,GIF,bmp,jpg,jpeg,png,gif";

	/**
	 * 上传文件
	 * @Author lililiang
	 * @Date 2021/7/9 16:28
	 */
	@SneakyThrows(Exception.class)
	public String upload(String filePath, String fileName, InputStream stream) {
		String fileTyle = fileName.substring(fileName.lastIndexOf(".")+1);

		// 检查存储桶是否已经存在
		boolean isExist = client.bucketExists(bucket);
		if(!isExist){
			client.makeBucket(bucket);
		}
		// 使用putObject上传一个文件到存储桶中。
		if(StrUtil.isNotEmpty(filePath)) {
			fileName = filePath + RandomUtils.getUUID() + "_" + fileName;
		}else{
			fileName = RandomUtils.getUUID() + "_" + fileName;
		}
		PutObjectOptions putObjectOptions = new PutObjectOptions(Long.valueOf(stream.available()), -1);
		if(IMGSUF.indexOf(fileTyle) >= 0){
			// 图片文件设置contentType,可以在浏览器直接打开
			putObjectOptions.setContentType("image/jpeg");
		}
		client.putObject(bucket, fileName, stream, putObjectOptions);
		String fileUrl = client.presignedGetObject(bucket, fileName);
		return fileUrl.substring(0, fileUrl.indexOf("?"));
	}


	/**
	 * 上传文件
	 * @Author lililiang
	 * @Date 2021/7/9 16:28
	 */
	@SneakyThrows(Exception.class)
	public String upload(MultipartFile file) {
		return this.upload(null, file.getOriginalFilename(), file.getInputStream());
	}

	/**
	 * 上传文件
	 * @Author lililiang
	 * @Date 2021/7/9 16:28
	 */
	@SneakyThrows(Exception.class)
	public String upload(String filePath, MultipartFile file) {
		return this.upload(filePath, file.getOriginalFilename(), file.getInputStream());
	}

}

